import logging
import random

from rest_framework import status

from verification import constants
from celery_tasks.sms.tasks import send_sms_code

# Create your views here.
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView

from meiduo_mall.utils.exceptions import logger

logger = logging.getLogger("django")

class SMSCodeView(APIView):
    """发送短信验证码"""
    def get(self,request,mobile):
        # 生成和发送短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        # 创建连接到redis的对象
        redis_conn = get_redis_connection('verify_codes')

        # 60秒内不允许重复发送验证码
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            return Response({"message":"短信发送过于频繁"},status=status.HTTP_400_BAD_REQUEST)

        logger.info(sms_code)

        # 以下代码演示redis管道pipeline的使用
        pl = redis_conn.pipeline()
        # 把验证码储存到redis中
        # redis_conn.setex(key, 过期时间, value)
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)

        # 储存此手机已经发送短信标记
        # redis_conn.setex('send_flag_%s' % mobile,constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.setex('send_flag_%s' % mobile,constants.SEND_SMS_CODE_INTERVAL, 1)

        # 执行
        pl.execute()

        # CCP().send_template_sms(mobile,[sms_code,constants.SMS_CODE_REDIS_EXPIRES//60],1)

        send_sms_code.delay(mobile, sms_code)

        # 响应发送短信验证码结果
        return Response({"massage":"OK"})















